package com.alpesressources.comexpert.util;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.alpesressources.comexpert.bo.ObjectContainer;
import com.alpesressources.comexpert.bo.IObject;


public class MyMarshaller {
	private JAXBContext context;

	public MyMarshaller(Class<?> containerClass, Class<?> objectClass)
			throws JAXBException {
		context = JAXBContext.newInstance(containerClass, objectClass);
	}

	public MyMarshaller(Class<?> objectClass) throws JAXBException {
		context = JAXBContext.newInstance(objectClass);
	}

	public String marshall(IObject object) throws JAXBException {

		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		StringWriter writer = new StringWriter();

		marshaller.marshal(object, writer);

		return writer.toString();
	}

	public IObject unMarshallObject(InputStream is) throws JAXBException {
		Unmarshaller unMarshaller = context.createUnmarshaller();
		return (IObject) unMarshaller.unmarshal(is);
	}

	public ObjectContainer unMarshallContainer(InputStream is) throws JAXBException {
		Unmarshaller unMarshaller = context.createUnmarshaller();
		return (ObjectContainer) unMarshaller.unmarshal(is);
	}
}
